var root = new Vue({
    el: "#rootDiv",
    data: {
        groups: [],
        apis: {}
    },
    methods: {
        submit: submitForm
    },
    filters: {
        formatModel: function (value) {
            return formatModel(value);
        },
        schemaFormat: function (value) {
            if (value) {
                return value.type || value.$ref.replace('#/definitions/', '');
            } else {
                return "";
            }
        }
    }
});

function formatModel(value) {
    try {
        var typeValue = {'string': "", 'int': 0, 'integer': 0, 'object': {}};
        var modelName = value[200].schema.type || value[200].schema.$ref.replace('#/definitions/', '');
        var definitions = root.apis.definitions;
        if (definitions[modelName]) {
            var properties = definitions[modelName].properties;
            var returnValue = {};
            $.each(properties, function (k, v) {
                returnValue[k] = typeValue[v.type]
            });
            return returnValue;
        } else {
            if (modelName === 'string') {
                return '""'
            }
            return typeValue[modelName.trim()];
        }
    } catch (e) {
        return "";
    }
}

$(document).ready(function () {
    $("input").click(function () {
        $(this).removeClass('input-border-color');
    });
    $("#groups").change(function () {
        initApi($("#groups").val());
    });
});

function init() {
    while (!$("#agreement").val()) {
        $("#agreement").val(prompt("Please set up IP and port,ip and port is not null.", 'http'));
    }
    while (!$("#domain").val()) {
        $("#domain").val(prompt("Please set up IP and port,ip and port is not null.", 'localhost'));
    }
    while (!$("#port").val()) {
        $("#port").val(prompt("Please set up IP and port,ip and port is not null.", '8081'));
    }
    initGroups();
}

function initGroups() {
    var requestParam = {
        agreement: $("#agreement").val(),
        domain: $("#domain").val(),
        port: $("#port").val(),
        path: "zfs/api/initPackage",
        method: "GET"
    };
    $.ajax({
        url: "getBasic",
        data: requestParam,
        type: "GET",
        async: false,//true为异步，false为同步
        success: function (result) {
            result = JSON.parse(result);
            root.groups = result;
            initApi(result[0]);
        }
    });
}

function initApi(apiPath) {
    var requestParam = {
        agreement: $("#agreement").val(),
        domain: $("#domain").val(),
        port: $("#port").val(),
        path: apiPath,
        method: "GET"
    };
    $.ajax({
        url: "getBasic",
        data: requestParam,
        type: "GET",
        async: false,//true为异步，false为同步
        success: function (result) {
            result = JSON.parse(result);
            root.apis = result;
        }
    });
}

function submitForm(formId, url) {
    if (formCheck(formId)) {
        var properties = $("#" + formId).serializeArray();
        var type = 'GET';
        var contentType = '*/*';
        $.each(properties, function (index, proper) {
            if (proper.name === 'type') {
                type = proper.value;
            } else if (proper.name === 'contentType') {
                contentType = proper.value;
            }
        });
        var requestParam = {
            agreement: $("#agreement").val(),
            domain: $("#domain").val(),
            port: $("#port").val(),
            path: url,
            param: $("#" + formId).serialize(),
            method: type
        };
        headerMap['Accept'] = contentType || "application/json; charset=utf-8";
        $.ajax({
            headers: headerMap,
            url: "getBasic",
            data: requestParam,
            type: "GET",
            dataType: 'TEXT',
            async: true,//true为异步，false为同步
            success: function (result) {
                try {
                    $("#rbc-" + formId).jsonViewer(JSON.parse(result), {collapsed: false});
                } catch (e) {
                    console.info(e);
                    $("#rbc-" + formId).text(result);
                } finally {

                }
            }
        });
    }
}

function formCheck(formId) {
    var flag = true;
    var inputDoms = $("#" + formId + " input");
    $.each(inputDoms, function (index, inpuDom) {
        if ($(inpuDom).attr('required')) {
            if (!$(inpuDom).val()) {
                flag = false;
                $(inpuDom).addClass('input-border-color');
                // $(inpuDom).after('<i class="fa fa-times-circle has-error">is not null</i>');
                $(inpuDom).keydown(function () {
                    $(inpuDom).removeClass('input-border-color');
                    // $(inpuDom).next().remove();
                })
            }
        }
    });
    return flag;
}

function checkboxRemoveDisabled(flag, idFlag) {
    var key = $("#" + flag + "key-" + idFlag).val();
    var value = $("#" + flag + "value-" + idFlag).val();
    if (key && value) {
        $("#" + flag + "checkbox-" + idFlag).iCheck('enable')
    } else {
        $("#" + flag + "checkbox-" + idFlag).iCheck('disable')
    }
}